import {
  Geometry,
  Mesh,
  ShaderMaterial,
  TSVector2,
  TextureLoader,
  TwinSpace2D,
} from "twinspace2d";
import normalFrag from "./shader/normal.frag";
import normalVert from "./shader/normal.vert";
import tex from "./demo2.jpg";

const N2D = new TwinSpace2D("normalConvert");
const geometry = new Geometry();
const width = N2D.canvas.clientWidth;
const height = N2D.canvas.clientHeight;
geometry.setAttribute(
  "u_position",
  new Float32Array([
    0,
    0,
    width,
    0,
    width,
    height,
    width,
    height,
    0,
    height,
    0,
    0,
  ]),
  2
);

geometry.setAttribute(
  "uv",
  new Float32Array([0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0]),
  2
);

const material = new ShaderMaterial({
  uniforms: {
    u_resolution: {
      value: new TSVector2(N2D.canvas.clientWidth, N2D.canvas.clientHeight),
    },
    u_texture: {
      value: new TextureLoader().load(tex, (map) => {
        map.repeat = "repeat";
      }),
    },
  },
  fragmentShader: normalFrag,
  vertexShader: normalVert,
});

const mesh = new Mesh(geometry, material);

N2D.scene.add(mesh);

window.addEventListener("resize", () => {
  material.uniforms.u_resolution.value = new TSVector2(
    N2D.canvas.clientWidth,
    N2D.canvas.clientHeight
  );
});

const render = () => {
  requestAnimationFrame(render);
  N2D.render();
};

render();
